package control

import (
	shadow "FlyFight/Internal/Shadow"
	"FlyFight/Internal/game"
	"FlyFight/Internal/room"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
)

func AddRoom(c *gin.Context){
	token := c.Query("token")
	cl,err:=shadow.ParseToken(token)
	if err!=nil{
		log.Println("Invalid token:", err)
		return
	}
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("WebSocket 升级失败:", err)
		return
	}
	var mes Wmessage
	err=conn.ReadJSON(&mes)
	if err!=nil{
		conn.Close()
		log.Println("read message error:",err)
		return
	}
	rid,err:=strconv.Atoi(mes.Data)
	if err!=nil{
		conn.Close()
		log.Println("turn to int error:",err)
		return
	}
	err=room.ConnectRoom(uint32(cl.UserID),cl.Username,rid,conn)
	if err != nil {
		conn.Close()
		log.Println("connect room error:", err)
		return
	}

}

func ConnectGame(c *gin.Context) { 
	token:=c.Query("token")
	cl,err:=shadow.ParseToken(token)
	if err!=nil{
		log.Println("token解析失败")
		return
	}
	roomId,err:=strconv.Atoi(c.Query("roomid"))
	if err!=nil{
		log.Println("roomid转换失败")
		return
	}
	// uuid:=c.Query("uuid")
	r,ok:=room.RoomList[roomId]
	if !ok{
		log.Println("房间不存在")
		return
	}
	// if !r.CheckUuid(uuid){
	// 	log.Println("uuid错误")
	// 	return
	// }
	if !r.CheckExist(uint32(cl.UserID)) {
		log.Println("用户不存在")
		return
	}


	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("升级失败")
		return
	}
	g:=game.Gman.Get(roomId)
	if g==nil{
		log.Println("游戏不存在 创建游戏")
		g=game.BuildGame(roomId)
		game.Gman.Add(g)
	}

	err=g.TryConnect(uint32(cl.UserID),conn)
	if err!=nil{
		log.Println(err)
		conn.Close()
		return
	}


}
